<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring WebFlux Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        #greetingResponse {
            margin-top: 20px;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
<h1>流式访问Ai</h1>
选择AI智能体<select id="appselect" name="appSelect">
    <option value="langchain4j">langchain4j(字符串回显)</option>
    <option value="springai">springai(Json回显)</option>
    <option value="springaiChatString">springai(字符串回显)</option>
</select>
<br/><br/>
<textarea id="nameInput" rows="5" cols="50" placeholder="Enter your quersiton"></textarea>
<button id="greetBtn">Greet Me!</button>
<div id="greetingResponse"></div>

<script>
    let previousContent = ""; // 用于跟踪已显示的内容，避免重复

    async function sendGreetingRequest() {
        const name = document.getElementById('nameInput').value;
        const appSelect = document.getElementById('appselect');

        if (appSelect.value === 'springai') {
            url = `http://127.0.0.1:9999/springaiChat/message3?message=${encodeURIComponent(name)}`;
        } else if(appSelect.value === 'springaiChatString'){
            url = `http://127.0.0.1:9999/springaiChat/chat2?message=${encodeURIComponent(name)}&uuid=2`;
        }else {
            url = `http://127.0.0.1:9998/langchain4jChat/steamAssistant?message=${encodeURIComponent(name)}`;
        }

        try {
            const response = await fetch(url);
            const reader = response.body.getReader();
            const decoder = new TextDecoder("utf-8");
            let result = '';

            // 流式读取内容
            reader.read().then(function processText({done, value}) {
                if (done) {
                    console.log("Stream finished.");
                    return;
                }

                if (appSelect.value === 'springai') {

                    result += decoder.decode(value, {stream: true});
                    const messages = result.split('\n').filter(line => line.trim());
                    // 遍历每条消息并逐步显示内容
                    messages.forEach(message => {

                        if (message.startsWith('data:')) {
                            const jsonData = JSON.parse(message.substring(5)); // 去掉 'data:' 前缀
                            appendMessage(jsonData);
                        } else {
                            const jsonData = JSON.parse(message); // 去掉 'data:' 前缀
                            appendMessage(jsonData);
                        }
                    });
                } else {
                    result = decoder.decode(value, {stream: true});
                    appendMessage2(result);
                }

                // 继续读取下一块数据
                reader.read().then(processText);
            });
        } catch (error) {
            console.error('Error:', error);
        }
    }

    function appendMessage(jsonData) {

        const content = jsonData.result.output.content;

        // 只显示新的内容
        if (content && !previousContent.includes(content)) {
            previousContent += content;
            displayMessage(content);
        }
    }

    function appendMessage2(message) {
        console.log(message, previousContent);
        const content = message;

        // 只显示新的内容
        if (content && !previousContent.includes(content)) {
            previousContent += content;
            displayMessage(content);
        }
    }

    function displayMessage(content) {
        const responseDiv = document.getElementById('greetingResponse');
        responseDiv.innerText += content; // 显示逐步返回的内容
    }

    function clearMessages() {
        const responseDiv = document.getElementById('greetingResponse');
        responseDiv.innerHTML = ''; // 清空所有内容
        previousContent = ""; // 重置已显示内容
    }

    document.getElementById('greetBtn').addEventListener('click', function () {
        clearMessages();
        sendGreetingRequest();
    });
</script>
</body>
</html>
